import utime as time
import gc

import mod_network
import mod_485
import mod_mqtt
import mod_led
import mod_time
import mod_system
import mod_ttl
import config
import mod_relay
import mod_adc
import service_storage
import service_data
# import service_warning


def main():
    """主函数 - 极简启动逻辑"""

    config.init()
    
    print("[MAIN] === HEAYUN HaaS506 DTU Starting ===")
    time.sleep(1)  # 系统启动延时

    # 7. mod_relay
    mod_relay.init()
    time.sleep(1)

    # 8. mod_adc
    mod_adc.init()
    time.sleep(1)

    # 初始化系统服务-记录重启次数
    mod_system.init()
    time.sleep(1)

    # 8. mod_ttl
    mod_ttl.init()
    time.sleep(1)

    # 初始化模块
    # 2. mod_network
    mod_network.init()
    time.sleep(1)
    # print("[MAIN] ===> Network module initialized")
    # 3. mod_time (不立即同步时间)
    mod_time.init()
    time.sleep(1)
    # 4. mod_485
    mod_485.init()
    time.sleep(1)
    # 5. mod_mqtt
    mod_mqtt.init()
    time.sleep(1)

    # 6. mod_led
    mod_led.init()
    time.sleep(1)

    # 初始化数据服务
    service_storage.runtime_storage.init_kv_storage()
    data_collector = service_data.runtime_data_collector

    print("[MAIN] === System Ready ===")

    # 设置系统状态为运行中
    config.g_system_status = "running"

    # 获取配置间隔
    intervals = config.get_intervals()
    data_collection_interval = intervals.get("data_collection", 10)
    mqtt_upload_interval = intervals.get("mqtt_upload", 30)
    network_check_interval = intervals.get("network_check", 60)

    print(
        "[MAIN] Using intervals - Data:{}, MQTT:{}, Network:{}".format(
            data_collection_interval,
            mqtt_upload_interval,
            network_check_interval,
        )
    )

    # 主循环计数器
    loop_count = 0

    print("[MAIN] ===> system version: {}".format(config.get_config("system.version")))

    # 主循环 - 依赖看门狗自动重启
    while True:
        loop_count += 1
        # service_warning.runtime_warning_service.check_warning()
 
        # 检查网络状态并同步时间
        try:
            if hasattr(mod_network, "getNetFlag"):
                current_network_status = mod_network.getNetFlag()
            else:
                mod_network.connect_network()
                time.sleep(1)
                current_network_status = mod_network.getNetFlag()
            # 处理网络状态变化
            if current_network_status != config.g_network_ready:
                config.g_network_ready = current_network_status

                if config.g_network_ready and not config.g_time_synced:
                    print("[MAIN] Network connected, syncing time")
                    if hasattr(mod_time, "sync_time") and mod_time.sync_time():
                        config.g_time_synced = True
                    else:
                        print("[MAIN] Time sync failed")
        except:
            config.g_network_ready = False
            print("[MAIN] Network check failed")

        # 检查MQTT连接状态
        config.g_mqtt_connected = mod_mqtt.is_connected()
        if config.g_mqtt_connected == False:
            # 连接成功后，立即同步flash缓存
            print(
                "[MAIN] Data check config.g_mqtt_connected:{}".format(
                    config.g_mqtt_connected
                )
            )

        # LED状态由mod_led模块直接监听全局变量，无需手动更新

        # 高频检查MQTT控制消息，确保实时响应服务器指令
        if mod_mqtt.is_connected():
            mod_mqtt.check_control_messages()

        # 数据收集
        if loop_count % data_collection_interval == 0 and data_collector:
            try:
                data = data_collector.collect_data()
            except:
                pass

        # network_check_interval 定期检查网络
        if loop_count % network_check_interval == 0:
            if not mod_network.getNetFlag():
                print("[MAIN] Network disconnected, reconnecting")
                mod_network.connect_network()

        # MQTT上传 (仅在网络连接时)
        if (
            loop_count % mqtt_upload_interval == 0
            and data_collector
            and config.g_mqtt_connected
        ):
            try:
                data_collector.push_data()
            except:
                print("[MAIN] MQTT upload failed")
                pass

        # 网络重连检查已移至MQTT模块定时器处理，此处移除避免冲突

        # 处理TTL命令 (每次循环都检查)
        try:
            if hasattr(mod_ttl, "process_command"):
                result = mod_ttl.process_command()
                # 如果处理了命令，记录日志
                if result:
                    print("[MAIN] TTL command processed")
        except Exception as e:
            print("[MAIN] TTL command processing error: {}".format(e))

        # 定期补传 flash 卡里的数据
        if loop_count % 60 == 0 and data_collector:
            try:
                data_collector.push_data()
            except Exception as e:
                print("[MAIN] Flash cache upload failed: {}".format(e))

        # 内存回收 (每300秒)
        if loop_count % 300 == 0:
            gc.collect()
            print(
                "[MAIN] Loop #{}, Memory: {}KB".format(
                    loop_count, gc.mem_free() // 1024
                )
            )

        # 重置计数器
        if loop_count >= 3600:  # 1小时重置
            loop_count = 0

        time.sleep(1)


if __name__ == "__main__":
    main()
